<template>
  <div>
    <van-index-bar :index-list="indexList" @select="selectChar">
      <div :key='index' v-for='(data,index) in cities'>
        <van-index-anchor :index="data.index" />
        <van-cell @click='clickCity(item)' v-for='(item,index) in data.list' :key='index' :title="item.name" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import { IndexBar, IndexAnchor, Cell, Toast } from 'vant'
import { instance } from '@/utils/http'
import { mapMutations } from 'vuex'
Vue.use(IndexBar)
Vue.use(IndexAnchor)
Vue.use(Cell)
export default {
  data() {
    return {
      cities: [],
      indexList: []
      // cities: [{ index: 'A', list: ['鞍山', '安阳', '安顺'] }, { index: 'B', list: ['北京', '包头', '保定'] }]
    }
  },
  async created() {
    const res = await instance.get('/gateway?k=319236', {
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    })
    this.filterDataList(res.data.data.cities)
  },
  methods: {
    ...mapMutations('city', ['setCityName', 'setCityId']),
    ...mapMutations('cinema', ['setCinemaList']),
    selectChar(index) {
      Toast({
        message: index
      })
    },
    clickCity(item) {
      // 需要将vuex的city的cityName进行设置
      this.setCityName(item.name)
      this.setCityId(item.cityId)
      // 将vuex的cinemaList数组清空一下
      this.setCinemaList([])
      // 编程式导航跳转
      this.$router.back()
    },
    filterDataList(cities) {
      // 生成26个大写字母
      const letterArr = []
      const cityArr = []
      for (let i = 65; i <= 90; i++) {
        letterArr.push(String.fromCharCode(i))
      }

      // 需要根据cities进行字母的筛选
      for (let i = 0; i < letterArr.length; i++) {
        const tempArr = cities.filter(item => item.pinyin.substr(0, 1).toUpperCase() === letterArr[i])
        if (tempArr.length) { // 如果cities里面有符合要求的城市的话
          cityArr.push({
            index: letterArr[i],
            list: tempArr
          })
          // 需要更改indexList数组
          this.indexList.push(letterArr[i])
        }
      }
      this.cities = cityArr
    }
  }
}
</script>

<style  lang='scss'>

</style>
